package ClientFront;

//import ClientFront.CONSTS.ClientConsts;
import ClientFront.Listeners.MsgReciver;
import ClientFront.Net.ConnectionInfo;


import javax.swing.*;
import java.awt.event.*;
import java.net.Inet4Address;

public class ClientLoginPanel extends MyPanel implements MsgReciver{
    //主面板
    JPanel mainPanel;
    //四个提示和三个输入框，确认按钮，主面板的组件
    JLabel userIPTip;
    JLabel serverIPTip;
    JTextField serverIPInput;
    JLabel userNameTip;
    JTextField userNameInput;
    JLabel serverPortTip;
    JTextField serverPortInput;
    JButton confirmBtn;
    //输入框中默认显示这些信息，如果不输入，默认以此连接。
    String serverIPInputStr = "192.168.1.15";
    String userPortInputStr = "9999";
    String userNameInputStr = "testUser";
    public String getUserName(){
        return userNameInput.getText();
    }

    public ClientLoginPanel(){
        setSize(MainWindow.LOGIN_PANEL_WIDTH,MainWindow.LOGIN_PANEL_HEIGHT);
        setLayout(null);
        mainPanel = new JPanel();
        initMainPanel();
        add(mainPanel);
    }

    private void initMainPanel(){
        int paddingx = 40;//所有组件左对齐宽度
        int paddingy = 50;//所有组件上方宽度
        int cpHeight = 25;//组件标准高
        int spacingy = 15;//组件标准上下间距
        mainPanel.setSize(this.getSize());
        mainPanel.setLayout(null);
        try{
            userIPTip = new JLabel("您的IP地址是："+ Inet4Address.getLocalHost().getHostAddress());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        userIPTip.setBounds(60,30,200,cpHeight);
        mainPanel.add(userIPTip);

        //三个标签和三个输入
        //输入中加了焦点监听，实现点击和离开输入时显示默认句子

        //服务器ip输入
        serverIPTip = new JLabel("服务器ip:");
        serverIPTip.setBounds(paddingx,paddingy+cpHeight+spacingy,50,cpHeight);
        mainPanel.add(serverIPTip);

        serverIPInput = new JTextField(serverIPInputStr);
        serverIPInput.setBounds(paddingx+60,paddingy+cpHeight+spacingy,150,cpHeight);
        serverIPInput.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                if(serverIPInputStr.equals(serverIPInput.getText())){
                    serverIPInput.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if("".equals(serverIPInput.getText().trim())){
                    serverIPInput.setText(serverIPInputStr);
                }
            }
        });
        mainPanel.add(serverIPInput);

        //服务器端口输入
        serverPortTip = new JLabel("端口：");
        serverPortTip.setBounds(paddingx,paddingy+cpHeight*2+spacingy*2,50,cpHeight);
        mainPanel.add(serverPortTip);

        serverPortInput = new JTextField(userPortInputStr);
        serverPortInput.setBounds(paddingx+60,paddingy + cpHeight*2+spacingy*2,150,cpHeight);
        serverPortInput.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                if(userPortInputStr.equals(serverPortInput.getText())){
                    serverPortInput.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if("".equals(serverPortInput.getText().trim())){
                    serverPortInput.setText(userPortInputStr);
                }
            }
        });
        mainPanel.add(serverPortInput);


        userNameTip = new JLabel("用户名:");
        userNameTip.setBounds(paddingx,paddingy + cpHeight*3+spacingy*3,50,cpHeight);
        mainPanel.add(userNameTip);

        userNameInput = new JTextField(userNameInputStr);
        userNameInput.setBounds(paddingx+60,paddingy + cpHeight*3+spacingy*3,150,cpHeight);
        userNameInput.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                if(userNameInputStr.equals(userNameInput.getText())){
                    userNameInput.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if("".equals(userNameInput.getText().trim())){
                    userNameInput.setText(userNameInputStr);
                }
            }
        });
        userNameInput.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if(e.getKeyChar() == KeyEvent.VK_ENTER){
                    confirmBtn.doClick();
                }
            }
        });
        mainPanel.add(userNameInput);

        confirmBtn = new JButton("连接");
        confirmBtn.setBounds(paddingx+35,paddingy +cpHeight*4+spacingy*5+30,140,cpHeight);
        confirmBtn.addActionListener(e -> linkToServer());
        mainPanel.add(confirmBtn);
    }

    private void linkToServer(){
        //验证输入是否有效
        if(!verifyAndResetWrongInput()){
            return;
        }
        //验证输入完成，开始准备进入，用填入的信息初始化NetMsgDealer
        initMsgDealer();
        //连接测试，交换用户名
        if(!msgDealer.init()){//连接失败，还在登录界面
            return;
        }
        //连接成功，获得彼此socket，切换到大厅界面

        parentWindowSwitch.switchPanelTo(MainWindow.gamePanelName);
    }

    private boolean verifyAndResetWrongInput(){
        //获得输入信息，去除多余空格
        String serverIP = serverIPInput.getText().trim();
        String id = userNameInput.getText().trim();
        String port = serverPortInput.getText().trim();
        //判断输入是否有效
        boolean isValidIP = MyUtils.isValidIPv4Address(serverIP);
        boolean isValidName = MyUtils.isValidUserName(id);
        boolean isValidPort = MyUtils.isValidPort(port);
        //错误则清空对应的输入框
        if(!isValidIP){
            serverIPInput.setText(serverIPInputStr);
        }
        if(!isValidName){
            userNameInput.setText(userNameInputStr);
        }
        if(!isValidPort){
            serverPortInput.setText(userPortInputStr);
        }
        //若输入错误，需要重新输入
        if(!isValidIP || !isValidName || !isValidPort) {
            JOptionPane.showMessageDialog(null, "您的输入有误", "提示", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        return true;
    }

    private void initMsgDealer() {
        //填写连接信息，放入MsgDealer
        ConnectionInfo connectionInfo = new ConnectionInfo();
        connectionInfo.setServerPort(Integer.parseInt(serverPortInput.getText().trim()));
        connectionInfo.setServerIpAddress(serverIPInput.getText().trim());
        //放入msgdealer
        msgDealer.setConnectionInfo(connectionInfo);
        msgDealer.setUserName(userNameInput.getText().trim());
        msgDealer.setMsgReciver(this);
    }

    @Override
    public void sendMsg(NetMsg msg) {
        dealMsg(msg);
    }

    void dealMsg(NetMsg msg){
        switch (msg.getMsgType()){
            case LINKERROR://连接测试时发生连接错误
                JOptionPane.showMessageDialog(null,"连接失败","提示",JOptionPane.ERROR_MESSAGE);
                break;
            case LINKACK://连接成功，返回服务器名
                JOptionPane.showMessageDialog(null,"连接成功,连接至服务器"+msg.getArgs()[0]);
                break;
            case CLIENT_TIP://连接提示，测试显示用
                System.out.println(msg.getArgs()[0]);
        }
    }
}
